package org.jdbcparser.rules;

import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;


public class RulesHelper {

	private static final String PARSER_IDS_CLASSPATH="/org/jdbcparser/parsing/";
	
	public static RulesHelper createHelperByParserId(String parserId) {
		URL parsingRulesURL = RulesHelper.class.getResource(PARSER_IDS_CLASSPATH + parserId + ".xml");
		return new RulesHelper(parsingRulesURL);
	}
	
	public static RulesHelper createHelperByParserURL(String parserURL) {
		URL parsingRulesURL;
		try {
			parsingRulesURL = new URL(parserURL);
			return new RulesHelper(parsingRulesURL);
		} catch (MalformedURLException e) {
			throw new IllegalArgumentException("Unable to find parsing rules file at '" + parserURL + "'", e);
		}
	}
	
	private RulesJDBCParser parsingJDBCParser;
	
	private RulesHelper(URL parsingRulesURL) {
		unmarshall(parsingRulesURL);
	}
	
	private void unmarshall(URL parsingRulesURL) {
		try {
			JAXBContext context = JAXBContext.newInstance(RulesJDBCParser.class);
			Marshaller marshaller = context.createMarshaller();
			marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);

			//read XML from array of bytes
			InputStream bais = parsingRulesURL.openStream();
			Unmarshaller unmarshaller = context.createUnmarshaller();
			Object o = unmarshaller.unmarshal(bais);

			//prove the Group is recreated
			parsingJDBCParser = (RulesJDBCParser) o;

		} catch (Exception e) {
			throw new IllegalArgumentException("Invalid parsing rules XML", e);
		}
	}

	public List<RulesTable> getTables() {
		return parsingJDBCParser.getTables();
	}

	public List<RulesIterator> getIterators() {
		return parsingJDBCParser.getIterators();
	}

}
